const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/db');
const crypto = require('crypto');

// 加密密钥的密码，应该从环境变量获取
const ENCRYPTION_KEY = process.env.API_KEY_ENCRYPTION_SECRET || 'your-32-char-secret-key-here-123';
const ALGORITHM = 'aes-256-cbc';

// 加密函数
function encrypt(text) {
  const iv = crypto.randomBytes(16);
  // 使用createCipheriv替代createCipher
  const cipher = crypto.createCipheriv(ALGORITHM, Buffer.from(ENCRYPTION_KEY).slice(0, 32), iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return iv.toString('hex') + ':' + encrypted;
}

// 解密函数
function decrypt(text) {
  try {
    const textParts = text.split(':');
    const iv = Buffer.from(textParts.shift(), 'hex');
    const encryptedText = textParts.join(':');
    // 使用createDecipheriv替代createDecipher
    const decipher = crypto.createDecipheriv(ALGORITHM, Buffer.from(ENCRYPTION_KEY).slice(0, 32), iv);
    let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
  } catch (error) {
    console.error('解密失败:', error);
    return null;
  }
}

const ApiKey = sequelize.define('ApiKey', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: 'API密钥名称/描述'
  },
  provider: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: 'API提供商'
  },
  api_key: {
    type: DataTypes.TEXT,
    allowNull: false,
    comment: '加密后的API密钥'
  },
  is_active: {
    type: DataTypes.BOOLEAN,
    defaultValue: true,
    comment: '是否启用'
  },
  usage_count: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    comment: '使用次数统计'
  },
  last_used_at: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '最后使用时间'
  },
  daily_limit: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '每日使用限制（可选）'
  },
  monthly_limit: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '每月使用限制（可选）'
  },
  created_by: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '创建者用户ID'
  },
  notes: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '备注信息'
  },
  api_config: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: 'API扩展配置信息'
  }
}, {
  tableName: 'api_keys',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  hooks: {
    // 保存前加密API密钥
    beforeCreate: (apiKey) => {
      if (apiKey.api_key) {
        apiKey.api_key = encrypt(apiKey.api_key);
      }
    },
    beforeUpdate: (apiKey) => {
      if (apiKey.changed('api_key') && apiKey.api_key) {
        apiKey.api_key = encrypt(apiKey.api_key);
      }
    }
  }
});

// 实例方法：获取解密后的API密钥
ApiKey.prototype.getDecryptedKey = function() {
  return decrypt(this.api_key);
};

// 实例方法：更新使用统计
ApiKey.prototype.updateUsage = async function() {
  this.usage_count += 1;
  this.last_used_at = new Date();
  await this.save();
};

// 静态方法：根据提供商获取可用的API密钥
ApiKey.getActiveKeyByProvider = async function(provider) {
  const apiKey = await ApiKey.findOne({
    where: {
      provider: provider,
      is_active: true
    },
    order: [['usage_count', 'ASC']] // 优先使用使用次数少的密钥
  });
  
  if (apiKey) {
    // 更新使用统计
    await apiKey.updateUsage();
    return apiKey.getDecryptedKey();
  }
  
  return null;
};

// 静态方法：获取所有提供商的可用密钥
ApiKey.getAllActiveKeys = async function() {
  const apiKeys = await ApiKey.findAll({
    where: {
      is_active: true
    },
    attributes: ['id', 'name', 'provider', 'usage_count', 'last_used_at'],
    order: [['provider', 'ASC'], ['usage_count', 'ASC']]
  });
  
  const result = {};
  for (const key of apiKeys) {
    if (!result[key.provider]) {
      result[key.provider] = [];
    }
    result[key.provider].push({
      id: key.id,
      name: key.name,
      usage_count: key.usage_count,
      last_used_at: key.last_used_at
    });
  }
  
  return result;
};

module.exports = ApiKey;
